<template>
  <div class="login-box">
    <a-form
        :model="formState"
        autocomplete="off"
        @finish="onFinish"
    >
      <a-form-item
          label="账号"
          v-bind="validateInfos.username"
      >
        <a-input v-model:value="formState.username"/>
      </a-form-item>

      <a-form-item
          label="密码"
          v-bind="validateInfos.password"
      >
        <a-input-password v-model:value="formState.password"/>
      </a-form-item>

      <!--      <a-form-item v-bind="validateInfos.remember">-->
      <!--        <a-checkbox v-model:checked="formState.remember">七天免登陆</a-checkbox>-->
      <!--      </a-form-item>-->

      <a-form-item :wrapper-col="{ offset: 7}">
        <a-button type="primary" html-type="submit" style="margin-right: 10px">登录</a-button>
        <a-button type="primary" @click="resetFields">重置</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import {reactive, toRaw} from 'vue';
import {useForm} from "ant-design-vue/es/form";
import {useRouter} from "vue-router";
import {login} from "@/api/api";
import type {AxiosResponse} from "axios";
import Cookie from "js-cookie"
import {message} from "ant-design-vue";

// 路由
const router = useRouter()

interface FormState {
  username: string;
  password: string;
  remember: boolean;
}

// 初始值
const formState = reactive<FormState>({
  username: '',
  password: '',
  remember: true,
});

// 字段校验
const ruleRef = reactive({
  username: [
    {
      required: true,
      message: "请输入您的账号"
    }
  ],
  password: [
    {
      required: true,
      message: "请输入您的密码"
    }
  ],
})

// 获取事件
const {resetFields, validate, validateInfos} = useForm(formState, ruleRef)

// 表单提交
const onFinish = () => {
  validate()
      // 获取成功
      .then(() => {
        const data = toRaw(formState);
        const {username, password} = data;
        login({username, password}).then(async (r: AxiosResponse) => {
          const {token} = r.data.data.data;
          Cookie.set("token", token);
          window.location.href = "/home";
          // 存储self全局状态
        }, async (err) => {
          await message.error(err)
        })
      })
};
</script>

<style>
.login-box {
  width: 320px;
  margin: 0 auto;
}
</style>